<?php
class CampaignController extends Zend_Controller_Action
{
	public function init()
	{
		Application_Helper_Authenticate::checkLogin($this);
	}
	
	public function indexAction()
	{
		$mUsers = new Application_Model_DbTable_User();
		$mCampaigns = new Application_Model_DbTable_Campaign();
		
		$campaigns = $mCampaigns->fetchAll()->toArray();
		
		foreach ($campaigns as $index => $campaign)
		{
			$uid = $campaign['created_user'];
			$time = $campaign['created_time'];
			
			$campaigns[$index]['created_username'] = $mUsers->getUsername($uid);
			$campaigns[$index]['created_date'] = date('d-m-Y', $time);
		}
		
		$this->view->campaigns = $campaigns;
	}
	
	public function addAction()
	{
		$form = new Application_Form_Campaign();
		$form->submit->setLabel('Add');
		$this->view->form = $form;
		 
		if ($this->getRequest()->isPost())
		{
			$formData = $this->getRequest()->getPost();
			 
			if ($form->isValid($formData))
			{
				$title = $form->getValue('title');
				$body = $form->getValue('body');
				$userid = Application_Helper_Authenticate::getUid();
				
				$campaign = new Application_Model_DbTable_Campaign();
				$campaign->addCampaign($title, $body, $userid);
	
				$this->_helper->redirector('index');
			}
			else
			{
				$form->populate($formData);
			}
		}
	}
	
	public function editAction()
	{
		$form = new Application_Form_Campaign();
		$form->submit->setLabel('Save');
		$this->view->form = $form;
	
		$this->view->title = 'Album edit';
	
		if ($this->getRequest()->isPost()) 
		{
			$formData = $this->getRequest()->getPost();
			
			if ($form->isValid($formData)) 
			{
				$id = (int)$form->getValue('id');
				$title = $form->getValue('title');
				$body = $form->getValue('body');
				
				$mCampaign = new Application_Model_DbTable_Campaign();
				$mCampaign->updateCampaign($id, $title, $body);
	
				$this->_helper->redirector('index');
			} 
			else 
			{
				$form->populate($formData);
			}
		} 
		else 
		{
			$id = $this->_getParam('id', 0);
			if ($id > 0) 
			{
				$mCampaign = new Application_Model_DbTable_Campaign();
				$form->populate($mCampaign->getCampaign($id));
			}
		}
	
	}
	
	public function deleteAction()
	{
		if ($this->getRequest()->isPost())
		{
			$del = $this->getRequest()->getPost('del');
			 
			if ($del == 'Yes')
			{
				$id = $this->getRequest()->getPost('id');
	
				$mCampaign = new Application_Model_DbTable_Campaign();
	
				$mCampaign->deleteCampaign($id);
			}
			 
			$this->_helper->redirector('index');
		}
		else
		{
			$id = $this->_getParam('id', 0);
			
			$mCampaign = new Application_Model_DbTable_Campaign();
			$mUsers = new Application_Model_DbTable_User();
			
			$campaign = $mCampaign->getCampaign($id);
			
			$uid = $campaign['created_user'];
			
			$campaign['created_username'] = $mUsers->getUsername($uid);
			
			$this->view->campaign = $campaign;
		}
	}
}